//
//  SQTitleView.swift
//  SQPageView
//
//  Created by ToothBond on 2017/4/24.
//  Copyright © 2017年 rensq. All rights reserved.
//

import UIKit

protocol SQTitleViewDelegate : class{ //声明class，表示这个协议只能被类遵守
    func titleView(_ titleView : SQTitleView, targetIndex : Int)
}

class SQTitleView: UIView {
    
    weak var delegate : SQTitleViewDelegate?        //weak 需要修饰类
    
    fileprivate var titles : [String]
    fileprivate var style : SQPageStyle
    fileprivate var currentIndex : Int = 0
    fileprivate lazy var titlesLabels : [UILabel] = [UILabel]()
    fileprivate lazy var normalRGB : (CGFloat,CGFloat,CGFloat) = self.style.normalColoe.getRGBValue()
    fileprivate lazy var selectRGB : (CGFloat,CGFloat,CGFloat) = self.style.selectColor.getRGBValue()
    fileprivate lazy var deltaRGB : (CGFloat,CGFloat,CGFloat) = {
        let deltaR = self.selectRGB.0 - self.normalRGB.0
        let deltaG = self.selectRGB.1 - self.normalRGB.1
        let deltaB = self.selectRGB.2 - self.normalRGB.2
        return (deltaR,deltaG,deltaB)
    }()
    
    fileprivate lazy var scrollView : UIScrollView = {
        let scrollView = UIScrollView(frame: self.bounds)
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.scrollsToTop = false
        return scrollView
    }()
    
    fileprivate lazy var bottomLine : UIView = {
        let bottomLine = UIView()
        bottomLine.backgroundColor = self.style.bottomLineColor
        return bottomLine
    }()
    
    fileprivate lazy var coverView : UIView = {
        let coverView = UIView()
        coverView.backgroundColor = self.style.coverViewColor
        coverView.alpha = self.style.coverViewAlpha
        return coverView
    }()

    init(frame: CGRect,titles : [String], style : SQPageStyle) {
        self.titles = titles
        self.style = style
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension SQTitleView {
    fileprivate func setupUI() {
        addSubview(scrollView)
        setupTitleLabels()
        setupBottomLine()
        setupCoverView()
    }
    
    private func setupTitleLabels() {
        
        for (i, title) in titles.enumerated() {
            let titleLabel = UILabel()
            titleLabel.text = title
            titleLabel.tag = i
            titleLabel.textAlignment = .center
            titleLabel.textColor = i == 0 ? style.selectColor : style.normalColoe
            titleLabel.font = style.titleFont
            scrollView.addSubview(titleLabel)
            titlesLabels.append(titleLabel)
            titleLabel.isUserInteractionEnabled = true

            let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(tapGes:)))
            titleLabel.addGestureRecognizer(tapGes)
        }
        let labelY : CGFloat = 0
        let labelH : CGFloat = style.titleHeight
        var labelW : CGFloat = bounds.width/CGFloat(titles.count)
        var labelX : CGFloat = 0
        var totalX : CGFloat = style.titleMargin * 0.5
        
        for (i,titleLabel) in titlesLabels.enumerated() {
            if style.isScrollEnable {
                labelW = (titleLabel.text! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName:style.titleFont], context: nil).width
                labelX = totalX
                totalX += labelW + style.titleMargin
            }else{
                labelX = CGFloat(i) * labelW
            }
            titleLabel.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
        }
        if style.isScrollEnable {
            scrollView.contentSize = CGSize(width: totalX - 0.5*style.titleMargin, height: style.titleHeight)
        }
    }
    
    private func setupBottomLine() {
        if style.isShowBottomLine{
            scrollView.addSubview(bottomLine)
            bottomLine.frame = titlesLabels.first!.frame
            bottomLine.frame.size.height = style.bottomLineHeight
            bottomLine.frame.origin.y = style.titleHeight - style.bottomLineHeight
        }
    }
    
    private func setupCoverView (){
        if style.isShowCoverView {
            scrollView.insertSubview(coverView, at: 0)
            
            guard let firstLabel = titlesLabels.first else {return}
            var coverW : CGFloat = firstLabel.frame.width
            let coverH : CGFloat = style.coverViewHeight
            var coverX : CGFloat = firstLabel.frame.origin.x
            let coverY : CGFloat = (firstLabel.frame.height - style.coverViewHeight)/2
            
            if style.isScrollEnable {
                coverX -= style.coverViewMargin
                coverW += style.coverViewMargin*2
            }
            
            coverView.frame = CGRect(x: coverX, y: coverY, width: coverW, height: coverH)
            coverView.layer.cornerRadius = style.coverViewRadius
            coverView.layer.masksToBounds = true
        }
    }
}

extension SQTitleView {
    @objc func titleLabelClick(tapGes : UITapGestureRecognizer) {
        guard let targetLabel = tapGes.view as? UILabel else {
            return
        }
        guard targetLabel.tag != currentIndex else {
            return
        }
        adjustLabelTitles(targetLabel)
        
        //可选链  ?.  如果可选类型有值，则执行代码，没有值则忽略
        delegate?.titleView(self, targetIndex: currentIndex)

    }
    
    fileprivate func adjustLabelPosition() {
        if !style.isScrollEnable {return}
        
        let targetLabel = titlesLabels[currentIndex]
        var offset = targetLabel.center.x - scrollView.bounds.width/2
        let maxOffset = scrollView.contentSize.width - scrollView.bounds.width
        if offset < 0 {
            offset = 0
        }
        if offset > maxOffset {
            offset = maxOffset
        }
        scrollView.setContentOffset(CGPoint(x: offset, y: 0), animated: true)
    }
    
    fileprivate func adjustLabelTitles(_ targetLabel : UILabel) {
        let sourceLabel = titlesLabels[currentIndex]
        sourceLabel.textColor = style.normalColoe
        targetLabel.textColor = style.selectColor
        
        currentIndex = targetLabel.tag
        adjustLabelPosition()
        
        //修改bottomLine的frame
        if style.isShowBottomLine {
            bottomLine.frame.origin.x = targetLabel.frame.origin.x
            bottomLine.frame.size.width = targetLabel.frame.width
        }
        
        if style.isShowCoverView {
            self.coverView.frame.origin.x = style.isScrollEnable ? targetLabel.frame.origin.x - style.coverViewMargin : targetLabel.frame.origin.x
            self.coverView.frame.size.width = style.isScrollEnable ? targetLabel.frame.width + 2*style.coverViewMargin : targetLabel.frame.width
        }
    }
}

extension SQTitleView {
    func setCurrentIndex(_ index : Int) {
        let targetLabel = titlesLabels[index]
        adjustLabelTitles(targetLabel)
    }
}

extension SQTitleView : SQContentViewDelegate {
    func contentView(_ contentView: SQContentView, didEndScroll inIndex: Int) {
        currentIndex = inIndex
        adjustLabelPosition()
    }
    
    func contentView(_ contentView: SQContentView, sourceIndex: Int, targetIndex: Int, progress: CGFloat) {
        let sourceLabel = titlesLabels[sourceIndex]
        let targetLabel = titlesLabels[targetIndex]
        
        sourceLabel.textColor = UIColor(r: selectRGB.0 - deltaRGB.0*progress, g: selectRGB.1 - deltaRGB.1*progress, b: selectRGB.2 - deltaRGB.2*progress)
        targetLabel.textColor = UIColor(r: normalRGB.0 + deltaRGB.0*progress, g: normalRGB.1 + deltaRGB.1*progress, b: normalRGB.2 + deltaRGB.2*progress)
        
        //修改bottomLine的frame
        let deltaX = (targetLabel.frame.origin.x - sourceLabel.frame.origin.x) * progress
        let deltaWidth = (targetLabel.frame.width - sourceLabel.frame.width) * progress
        if style.isShowBottomLine {
            let bottomX = sourceLabel.frame.origin.x + deltaX
            let bottomWidth = sourceLabel.frame.size.width + deltaWidth
            
            bottomLine.frame = CGRect(x: bottomX, y: bottomLine.frame.origin.y, width: bottomWidth, height: bottomLine.frame.height)
        }
        
        if style.isShowCoverView {
            if style.isScrollEnable {
                let coverX = sourceLabel.frame.origin.x + deltaX - style.coverViewMargin
                let bottomWidth = sourceLabel.frame.size.width + deltaWidth + 2*style.coverViewMargin
                
                coverView.frame = CGRect(x: coverX, y: coverView.frame.origin.y, width: bottomWidth, height: coverView.frame.size.height)
            }else{
                let coverX = sourceLabel.frame.origin.x + deltaX
                let bottomWidth = sourceLabel.frame.size.width + deltaWidth
                coverView.frame = CGRect(x: coverX, y: coverView.frame.origin.y, width: bottomWidth, height: coverView.frame.size.height)
            }
        }
    }
    
}


